package com.onepower.admin.core.security;

import com.onepower.core.modules.service.ISysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private  ISysRoleMenuService sysRoleMenuService;

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

    @SuppressWarnings("unchecked")
    private void loadResourceDefine() {
        Map<String, String> roleMap = sysRoleMenuService.getRoleMenuList();

        // 全局保存资源与角色映射
        resourceMap = new HashMap<>();
        // 遍历所有资源.resRolesMap的key为每一个资源的URL
        for (Iterator<String> url = roleMap.keySet().iterator(); url.hasNext();) {
            // 获取资源URL
            String resUrl = url.next();
            // 存放一个资源对应的角色列表
            Collection<ConfigAttribute> atts = new ArrayList<>();
            // 获取该资源所需的角色列表,以","分割的
            String[] role = roleMap.get(resUrl).split(",");
            for (int i = 0; i < role.length; i++) {
                // 转换成角色对象
                ConfigAttribute ca = new SecurityConfig(role[i]);
                // 将角色加入权限
                atts.add(ca);
                // 最终保存资源与角色的对应关系
                resourceMap.put(resUrl, atts);
            }
        }
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
//        loadResourceDefine();
//
//        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
//        // 获取需要拦截过滤的URL列表
//        for (String resURL : resourceMap.keySet()) {
//            // 遍历得到每一个需要过滤的URL
//            // 将当前访问的URL(url)与需要过滤的URL(resURL)进行比较，判断是否需要对当前请求的URL进行权限验证
//            RequestMatcher urlMatcher = new AntPathRequestMatcher(resURL);
//            if (urlMatcher.matches(request)) {
//                return resourceMap.get(resURL);
//            }
//        }
        // 如果在所有需要过滤的url中没有匹配到当前url，说明不需要对当前url进行过滤拦截，也不需要进行权限验证，所以就直接放行！页面可以直接访问到了
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
